package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.ExcelSubjectData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@AllArgsConstructor //有参
@NoArgsConstructor  //无参
public class ExcelSubjectDataListener extends AnalysisEventListener<ExcelSubjectData> {
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private SubjectMapper subjectMapper;
    /**
     *遍历每一行的记录,每次读一行都会调用这个方法
     * @param data
     * @param context
     */
    @Override
    public void invoke(ExcelSubjectData data, AnalysisContext context) {
        log.info("解析到一条记录:{} ",data);
        String levelOneTitle = data.getLevelOneTitle(); //一级标题
        String levelTwoTitle = data.getLevelTwoTitle(); //二级标题
        log.info("levelOneTitle: {}", levelOneTitle);
        log.info("levelTwoTitle: {}", levelTwoTitle);

        //存入数据库 subjectMapper.insert();
        //判断一级分类是否重复
        Subject subjectByTitleOne = this.getByTitle(levelOneTitle);
        String parentId = null;
        if (subjectByTitleOne == null) {
            //将一级分类存入数据库
            Subject subject = new Subject();
            subject.setTitle(levelOneTitle);
            subject.setParentId("0");
            subjectMapper.insert(subject);
             parentId = subject.getId();
        }else {
             parentId = subjectByTitleOne.getId();
        }
        //判断二级分类是否重复  根据以及分类的id
        Subject subjectSubByTitle = this.getSubByTitle(levelTwoTitle, parentId);
        if (subjectSubByTitle == null) {
            //将二级分类存入数据库
            Subject subject = new Subject();
            subject.setTitle(levelTwoTitle);
            subject.setParentId(parentId);
            subjectMapper.insert(subject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("解析到所有数据");
    }

    /**
     * 根据分类名称查询这个一级分类是否存在
     * @param title
     * @return
     */
    private Subject getByTitle(String title) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", "0");
        return subjectMapper.selectOne(queryWrapper);
    }

    /**
     * 根据这个二级分类名称和父id查询这个二级分类是否存在
     * @param title
     * @param parentId
     * @return
     */
    private Subject getSubByTitle(String title,String parentId) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", parentId);
        return subjectMapper.selectOne(queryWrapper);
    }
}
